package com.cheap.item.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheap.common.dto.PageDTO;
import com.cheap.common.enums.ComStatusEmun;
import com.cheap.common.pojo.po.Item;
import com.cheap.item.mapper.ItemMapper;
import com.cheap.item.service.IItemService;
import org.springframework.stereotype.Service;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    /**
     * 分页查询商品
     */
    @Override
    public PageDTO<Item> getListByPage(Integer page, Integer size) {
        IPage<Item> pageConfig = new Page<>(page, size);
        IPage<Item> resultPage = this.page(pageConfig);
        PageDTO<Item> result = new PageDTO<>();
        result.setTotal(resultPage.getTotal());
        result.setList(resultPage.getRecords());
        result.setPageSize(resultPage.getSize());
        return result;
    }

    /**
     * 商品上架、下架
     */
    @Override
    public void updateItemStatus(Long id, Integer status) {
        this.lambdaUpdate()
                .eq(Item::getId, id)
                .eq(Item::getStatus, status)
                .update();
    }

    /**
     * 修改商品
     */
    @Override
    public void updateInfoById(Item item) {
        boolean update = this.lambdaUpdate()
                .eq(Item::getId, item.getId())
                .eq(Item::getStatus, ComStatusEmun.BAD.getCode())
                .update(item);
        if (!update){
            throw new RuntimeException("上架商品不能修改，请先下架！");
        }
    }

    /**
     * 根据 id 删除商品
     */
    @Override
    public void deleteInfoById(Long id) {
        // 停用状态才能删除，而且还要抛错
        boolean remove = this.lambdaUpdate()
                .eq(Item::getId, id)
                .eq(Item::getStatus, ComStatusEmun.BAD.getCode())
                .remove();
        if (!remove){
            throw new RuntimeException("上架商品不能删除，请先下架！");
        }
    }


}
